<?php
// +----------------------------------------------------------------------
// | 多客怪兽框架多平台开发框架
// +----------------------------------------------------------------------
// | Copyright (c) 2021~2024 http://www.dkyx.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 刘泓宾（514660094@qq.com）
// +----------------------------------------------------------------------

namespace app\controller\adminapi\platform\app;

use app\common\model\platform\Platform;
use app\common\services\table\Column;
use app\common\services\table\DataForm;
use app\common\services\table\DataTable;
use app\common\model\platform\PlatformApp;
use app\common\controller\PlatformController;
use FormBuilder\Driver\CustomComponent;
use FormBuilder\Driver\FormComponent;
use hiduoke\services\FormBuilder as Form;

/**
 * Notes: 小程序应用管理列表
 * Create by :  刘泓宾<514660094@qq.com>
 * Copyright :  copyright (c) 多客怪兽, www.dkyx.cc
 * Created on:  2025/7/7 02:06
 */
class Addon extends PlatformController
{
    /**
     * @var PlatformApp
     */
    protected $model;


    // 设置关联查询
    protected array $withJoinTable = ['addons'];

    // 设置快捷搜索字段
    protected string|array $quickSearchField = [];

    /**
     * 控制器初始化
     * Create by :  刘泓宾<514660094@qq.com>
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();
        $this->model = new PlatformApp();
        $this->model->plaid = get_plaid();
        // 判断请求控制器方法
        if ($this->request->action() == "index" && !$this->request->param("select")) {
            // 定义全局的查询范围带有alias
            $this->model->setGlobalScope();
        }
    }

    /**
     * 数据表格
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function table()
    {
        $DataTable = (new DataTable($this->model));
        if ($this->request->param('recycle')) {
            // 回收站
            $DataTable->field([$this->model->getPk(), 'delete_time']);
        }
        $button = Column::make()->demoButton;
        $button['type'] = 'warning';
        // 按钮的属性参数
        $button['attr'] = [
            'style' => 'font-size:20px;',
            'size'  => 'large',
        ];
        $settingButton = array_merge($button, ['title' => '系统设置', "text" => "", 'icon' => 'Tools', 'name' => 'setting']);
        $jumpButton = array_merge($button, ['title' => '跳转访问', "text" => "", 'icon' => 'Promotion', 'name' => 'jump', 'type' => 'danger']);
        $column = $DataTable
            ->setHideFields(['aid', 'addon_name', 'addons.title'])
            ->setFilterFields(['uid', 'create_time', 'update_time', 'token', 'other_data', 'server_config', 'versions', 'name', 'logo'])
            ->setField('index', ['render' => 'switch'])
            ->setField('menu', ['render' => 'switch'])
            ->setField('version', ['render' => 'tag'])
            ->setField('app_type', ['custom' => ['dy' => 'danger', 'wx' => 'success']])
            ->setAfterFields([
                'id' =>
                [
                    [
                        'slotName'            => 'addon_solt',
                        'label'               => '应用',
                        'prop'                => 'addons.title',
                        'operator'            => 'LIKE',
                        'comSearchLabel'      => '应用名称',
                        'operatorPlaceholder' => '输入应用名称',
                        'align'               => 'center'
                    ],
                    [
                        'slotName'            => 'app_solt',
                        'label'               => '小程序',
                        'prop'                => 'name',
                        'operator'            => 'LIKE',
                        'comSearchLabel'      => '小程序名',
                        'operatorPlaceholder' => '输入小程序名称',
                        'align'               => 'center'
                    ]
                ]
            ])
            ->operation(
                Column::make()->prop('operation')
                    // 操作列标题
                    ->label('操作')
                    ->render('buttons')
                    // 宽度
                    ->width(100)
                    ->other('fixed', 'right')
                    // 禁用搜索
                    ->operator(false)
                    // 自定义按钮组
                    ->buttons([
                        $settingButton,
                        $jumpButton,
                    ])
                    ->create()
            )
            ->create();
        return $this->success('ok', ['column' => $column, 'pk' => $this->model->getPk()]);
    }

    /**
     * 数据表单
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function form()
    {
        return $this->error('禁止访问');
    }

    public function del(array $ids = [])
    {
        return $this->error('禁止访问');
    }

    /**
     * 获取数据列表
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     * @throws \Throwable
     * @throws \think\db\exception\DbException
     */
    public function index()
    {
        if ($this->request->param('select')) {
            return $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->append(['addon'])
            ->paginate($limit);
        return $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ], $this->model->getLastSql());
    }


    /**
     * 获取平台应用表单
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPlatformAddonAppForm()
    {
        $id = input("id", 0);
        $action = "/adminapi/platform.app.addon/platformAddonAppFormSave";
        $platform = (new Platform())->where(['plaid' => get_plaid()])->find();
        if (!$platform) {
            return $this->error('平台不存在');
        }
        if (!$id) {
            $id = $this->model->where(['plaid' => get_plaid(), 'addon_name' => get_addon()])->value('id');
        }
        if (!$id) {
            return $this->error('当前平台无小程序');
        }
        $rule = array();
        $form = Form::createForm($action)->setMethod("POST");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        $col = Form::col()->span(11)->offset(1)->pull(1);
        $rule[] = Form::hidden('id', $row->id);
        $rule[] = Form::switches('index', '首页显示', strval($row->index))->col($col)->effect(['help' => '显示到客户端首页']);
        $rule[] = Form::switches('menu', '菜单显示', strval($row->menu))->col($col)->effect(['help' => '显示到平台左侧列表页']);
        $rule[] = Form::dkImage('logo', '图标', $row['logo'] ?? '')->effect(['help' => '自定义小程序图标,方便区分']);
        $rule[] = Form::input('name', '名称', $row['name'] ?? '')->effect(['help' => '自定义小程序名称,方便区分']);
        $rule[] = Form::input('remark', '备注', $row['remark'] ?? '')->effect(['help' => '设置备注信息']);
        $rule[] = Form::input('sort', '排序', $row['sort']);
        if ($this->userInfo['is_admin']) {
            $rule[] = Form::input('token', 'Token', $row['token'] ?? '')->effect(['help' => '小程序应用秘钥，仅管理员可见，对应怪兽商城授权token'])->disabled(true);
        }
        $addon_rules = event($row['addon_name'] . '_platform_addon_config', $row['config'])[0] ?? [];
        if (!$addon_rules) {
            $instance = get_addons_instance($row['addon_name']);
            if ($instance !== null && method_exists($instance, 'platform_addon_config')) {
                $addon_rules = $instance->platform_addon_config($row['config']);
            }
        }
        if (is_array($addon_rules)) {
            foreach ($addon_rules as $key => $value) {
                if ($value instanceof FormComponent) {
                    $rule[] = $value;
                } elseif ($value instanceof CustomComponent) {
                    $rule[] = (new CustomComponent('elCol'))->appendChild($value)->props(['style' => 'margin-bottom:22px']);
                }
            }
        }
        $form->setTitle("平台应用小程序配置")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 平台应用小程序保存
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $formData
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function platformAddonAppFormSave($formData = [])
    {
        $id = $formData['id'];
        $res = $this->model->where(['id' => $id])->find();
        if ($res) {
            $res->index = $formData['index'];
            $res->menu = $formData['menu'];
            $res->sort = $formData['sort'];
            $res->logo = $formData['logo'];
            $res->name = $formData['name'];
            $res->remark = $formData['remark'];
            if (isset($formData['token'])) {
                $res->token = $formData['token'];
            }
            unset($formData['index']);
            unset($formData['menu']);
            unset($formData['sort']);
            unset($formData['logo']);
            unset($formData['name']);
            unset($formData['remark']);
            $res->config = $formData;
            $res->save();
            return $this->success("修改成功");
        } else {
            return $this->error('修改失败，未找到对应应用');
        }
    }
}
